<template>
  <div v-if="showExcel" class="xlsx">
    <div v-html="excelContent" />
    <el-pagination layout="prev, pager, next" :total="totalPages * 10" v-model:current-page="page"
      @current-change="readPage" />
  </div>
</template>

<script setup>
import axios from "axios";
import * as XLSX from "xlsx";
import { ref } from "vue";
import { ElMessage } from "element-plus";

const excelContent = ref();
const page = ref(1); // 当前页码
const totalPages = ref(1); // 总页数
let workbook
const showExcel = ref(false);

const open = async (url) => {
  try {
    const response = await axios.get(url, { responseType: 'arraybuffer' });
    workbook = XLSX.read(response.data, { type: 'array' });
    totalPages.value = workbook.SheetNames.length; // 设置总页数
    showExcel.value = true;
    readPage()

  } catch (error) {
    console.error("解析失败:", error);
    ElMessage.error("文件解析失败");
  }
};


const readPage = () => {
  const worksheet = workbook.Sheets[workbook.SheetNames[page.value]];
  excelContent.value = XLSX.utils.sheet_to_html(worksheet)
}
const close = () => {
  workbook = null;
  excelContent.value = "";
  showExcel.value = false;
}

defineExpose({
  open,
  close
})

</script>
<style scoped>
.xlsx {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
}

:deep(table) {
  border-collapse: collapse;
  width: 100%;
}

:deep(td, th) {
  border: 1px solid #ddd;
  padding: 8px;
}
</style>